package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bookstore.back.entity.Order;
import com.bookstore.back.entity.User;
import com.bookstore.back.mapper.UserMapper;
import com.bookstore.back.mapper.UserLogMapper;
import com.bookstore.back.service.*;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家服务实现类
 *
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserLogMapper userLogMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    @Override
    public Map<String, Object> getBusinessStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 图书总数 - 统计所有上架的图书
            QueryWrapper<com.bookstore.back.entity.Book> bookWrapper = new QueryWrapper<>();
            bookWrapper.eq("status", 1); // 只统计上架的图书
            long totalBooks = bookService.count(bookWrapper);
            stats.put("totalBooks", totalBooks);
            
            // 订单总数 - 统计所有订单
            long totalOrders = orderService.count();
            stats.put("totalOrders", totalOrders);
            
            // 总销售额 - 统计已支付、已发货、已完成订单的实付金额
            QueryWrapper<Order> salesWrapper = new QueryWrapper<>();
            salesWrapper.in("status", 1, 2, 3); // 已支付、已发货、已完成
            List<Order> paidOrders = orderService.list(salesWrapper);
            BigDecimal totalSales = paidOrders.stream()
                .map(Order::getActualAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
            stats.put("totalSales", totalSales);
            
            // 客户总数 - 统计有过订单的不重复用户数
            QueryWrapper<Order> customerWrapper = new QueryWrapper<>();
            customerWrapper.select("DISTINCT user_id");
            List<Order> orders = orderService.list(customerWrapper);
            long totalCustomers = orders.stream()
                .map(Order::getUserId)
                .distinct()
                .count();
            stats.put("totalCustomers", totalCustomers);
            
            log.info("商家业务统计数据获取成功: 图书{}本, 订单{}个, 销售额{}, 客户{}人", 
                totalBooks, totalOrders, totalSales, totalCustomers);
            
        } catch (Exception e) {
            log.error("获取商家业务统计数据失败：{}", e.getMessage());
            // 返回默认值
            stats.put("totalBooks", 0);
            stats.put("totalOrders", 0);
            stats.put("totalSales", BigDecimal.ZERO);
            stats.put("totalCustomers", 0);
        }
        
        return stats;
    }

    @Override
    public Map<String, Object> getMerchantProfile() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为商家
            if (!userContextUtil.isCurrentUserMerchant()) {
                throw new RuntimeException("权限不足，只有商家可以访问");
            }

            User merchant = userMapper.selectById(currentUserId);
            if (merchant == null) {
                return new HashMap<>();
            }
            
            Map<String, Object> profile = new HashMap<>();
            profile.put("id", merchant.getId());
            profile.put("username", merchant.getUsername());
            profile.put("email", merchant.getEmail());
            profile.put("phone", merchant.getPhone());
            profile.put("realName", merchant.getRealName());
            profile.put("avatar", merchant.getAvatar());
            profile.put("gender", merchant.getGender());
            profile.put("birthDate", merchant.getBirthDate());
            profile.put("balance", merchant.getBalance());
            profile.put("status", merchant.getStatus());
            profile.put("createTime", merchant.getCreateTime());
            profile.put("updateTime", merchant.getUpdateTime());
            
            return profile;
        } catch (Exception e) {
            log.error("获取商家个人资料失败：{}", e.getMessage());
            return new HashMap<>();
        }
    }

    @Override
    public boolean updateMerchantProfile(Map<String, Object> profileData) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为商家
            if (!userContextUtil.isCurrentUserMerchant()) {
                throw new RuntimeException("权限不足，只有商家可以访问");
            }

            User merchant = new User();
            merchant.setId(currentUserId);
            
            if (profileData.containsKey("realName")) {
                merchant.setRealName((String) profileData.get("realName"));
            }
            if (profileData.containsKey("email")) {
                merchant.setEmail((String) profileData.get("email"));
            }
            if (profileData.containsKey("phone")) {
                merchant.setPhone((String) profileData.get("phone"));
            }
            if (profileData.containsKey("gender")) {
                merchant.setGender((Integer) profileData.get("gender"));
            }
            if (profileData.containsKey("birthDate")) {
                // 这里需要处理日期格式转换
                // merchant.setBirthDate((Date) profileData.get("birthDate"));
            }
            
            return userService.updateById(merchant);
        } catch (Exception e) {
            log.error("更新商家个人资料失败：{}", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean changeMerchantPassword(Map<String, String> passwordData) throws RuntimeException {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为商家
            if (!userContextUtil.isCurrentUserMerchant()) {
                throw new RuntimeException("权限不足，只有商家可以访问");
            }

            String currentPassword = passwordData.get("currentPassword");
            String newPassword = passwordData.get("newPassword");
            String confirmPassword = passwordData.get("confirmPassword");

            if (currentPassword == null || newPassword == null || confirmPassword == null) {
                throw new RuntimeException("密码参数不完整");
            }

            if (!newPassword.equals(confirmPassword)) {
                throw new RuntimeException("新密码与确认密码不一致");
            }

            User merchant = userMapper.selectById(currentUserId);
            if (merchant == null) {
                throw new RuntimeException("商家不存在");
            }

            // 验证当前密码（明文比较，与登录逻辑保持一致）
            if (!currentPassword.equals(merchant.getPassword())) {
                throw new RuntimeException("当前密码错误");
            }

            // 验证新密码不能与当前密码相同
            if (currentPassword.equals(newPassword)) {
                throw new RuntimeException("新密码不能与当前密码相同");
            }

            // 更新密码（明文存储，与现有数据保持一致）
            merchant.setPassword(newPassword);
            merchant.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(merchant);
            if (result <= 0) {
                throw new RuntimeException("密码更新失败");
            }
            return true;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("修改商家密码失败：{}", e.getMessage());
            throw new RuntimeException("密码修改失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getMerchantStats() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为商家
            if (!userContextUtil.isCurrentUserMerchant()) {
                throw new RuntimeException("权限不足，只有商家可以访问");
            }

            Map<String, Object> stats = new HashMap<>();

            // 从用户日志表获取真实的统计数据
            Map<String, Object> userStats = userLogMapper.getUserStats(currentUserId);

            if (userStats != null) {
                // 登录次数
                Object loginCount = userStats.get("loginCount");
                stats.put("loginCount", loginCount != null ? loginCount : 0);

                // 操作次数
                Object operationCount = userStats.get("operationCount");
                stats.put("operationCount", operationCount != null ? operationCount : 0);

                // 最后登录时间
                Object lastLoginTime = userStats.get("lastLoginTime");
                stats.put("lastLoginTime", lastLoginTime != null ? lastLoginTime : "未知");

                // 最后登录IP
                Object lastLoginIp = userStats.get("lastLoginIp");
                stats.put("lastLoginIp", lastLoginIp != null ? lastLoginIp : "未知");
            } else {
                // 如果没有日志记录，返回默认值
                stats.put("loginCount", 0);
                stats.put("operationCount", 0);
                stats.put("lastLoginTime", "未知");
                stats.put("lastLoginIp", "未知");
            }

            // 获取商家注册时间
            User merchant = userMapper.selectById(currentUserId);
            if (merchant != null) {
                stats.put("registerTime", merchant.getCreateTime());
            }

            return stats;
        } catch (Exception e) {
            log.error("获取商家统计信息失败：{}", e.getMessage());
            // 返回默认值，避免前端报错
            Map<String, Object> defaultStats = new HashMap<>();
            defaultStats.put("loginCount", 0);
            defaultStats.put("operationCount", 0);
            defaultStats.put("lastLoginTime", "未知");
            defaultStats.put("lastLoginIp", "未知");
            return defaultStats;
        }
    }

    @Override
    public boolean updateMerchantAvatar(String avatarUrl) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为商家
            if (!userContextUtil.isCurrentUserMerchant()) {
                throw new RuntimeException("权限不足，只有商家可以访问");
            }

            User merchant = new User();
            merchant.setId(currentUserId);
            merchant.setAvatar(avatarUrl);
            merchant.setUpdateTime(LocalDateTime.now());

            return userService.updateById(merchant);
        } catch (Exception e) {
            log.error("更新商家头像失败：{}", e.getMessage());
            return false;
        }
    }
}
